<script setup lang="ts">
import {
  getClassPageList,
  addClass,
  updateClass,
  deleteClass,
  getAcademyList,
  updateAcademyList,
  deleteAcademyList,
  addAcademyList,
  getProfessionalList,
  updateProfessional,
  deleteProfessional,
  addProfessional,
  getAllClass,
  getAllProfessional,
  getAllAcademyList,
  addBatchClass
} from "@/api";
import { ref, onMounted, reactive, computed } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import type { TagProps, FormInstance, FormRules } from "element-plus";
import type { UploadFile, UploadFiles } from "element-plus";
import ExcelJS from "exceljs";

interface Class {
  id: number;
  name: string;
  code: string;
  grade: string;
  major_name: string;
  major_code: string;
  college_name: string;
  college_code: string;
}

interface Academy {
  id: number;
  name: string;
  code: string;
  created_at: string;
  updated_at: string;
}

interface Professional {
  id: number;
  name: string;
  code: string;
  college_name: string;
  college_code: string;
}

// 表格数据
const classData = ref<Class[]>([]);
const academyData = ref<Academy[]>([]);
const professionalData = ref<Professional[]>([]);
const loading = ref(false);
const activeTab = ref("class");

// 分页参数
const classPagination = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10
});

const academyPagination = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10
});

const professionalPagination = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10
});

// 标签类型列表
const tagTypes: TagProps["type"][] = [
  "success",
  "warning",
  "danger",
  "info",
  "primary"
];

// 颜色缓存
const collegeColorMap = ref<Map<string, TagProps["type"]>>(new Map());
const majorColorMap = ref<Map<string, TagProps["type"]>>(new Map());

// 获取或生成标签颜色
const getOrGenerateColor = (
  name: string,
  colorMap: Map<string, TagProps["type"]>
) => {
  if (!colorMap.has(name)) {
    const existingColors = Array.from(colorMap.values());
    const availableColors = tagTypes.filter(
      color => !existingColors.includes(color)
    );
    const color =
      availableColors.length > 0
        ? availableColors[0]
        : tagTypes[colorMap.size % tagTypes.length];
    colorMap.set(name, color);
  }
  return colorMap.get(name) || "info";
};

// 获取标签类型
const getCollegeTagType = (collegeName: string): TagProps["type"] => {
  return getOrGenerateColor(collegeName, collegeColorMap.value);
};

const getMajorTagType = (majorName: string): TagProps["type"] => {
  return getOrGenerateColor(majorName, majorColorMap.value);
};

// 树状数据
const treeData = ref([]);

// 添加学院列表数据
const allAcademies = ref<Academy[]>([]);
// 添加专业列表数据
const allProfessionals = ref<Professional[]>([]);

// 获取所有学院列表
const fetchAllAcademies = async () => {
  try {
    const res = await getAllAcademyList();
    if (res.status === "success" && res.data) {
      allAcademies.value = res.data;
    }
  } catch (error) {
    console.error("获取学院列表失败:", error);
    ElMessage.error("获取学院列表失败");
  }
};

// 获取所有专业列表
const fetchAllProfessionals = async () => {
  try {
    const res = await getAllProfessional();
    if (res.status === "success" && res.data) {
      allProfessionals.value = res.data;
    }
  } catch (error) {
    console.error("获取专业列表失败:", error);
    ElMessage.error("获取专业列表失败");
  }
};

// 获取树状数据
const fetchTreeData = async () => {
  try {
    loading.value = true;
    const [academyRes, professionalRes, classRes] = await Promise.all([
      getAllAcademyList(),
      getAllProfessional(),
      getAllClass()
    ]);

    console.log("学院数据:", academyRes.data);
    console.log("专业数据:", professionalRes.data);
    console.log("班级数据:", classRes.data);

    // 检查响应状态
    if (
      academyRes.status !== "success" ||
      !academyRes.data ||
      professionalRes.status !== "success" ||
      !professionalRes.data ||
      classRes.status !== "success" ||
      !classRes.data
    ) {
      throw new Error("数据格式错误");
    }

    // 构建树状数据
    const tree = academyRes.data.map(academy => {
      // 找到属于该学院的所有专业（通过 college_code 关联）
      const professionals = professionalRes.data
        .filter(prof => prof.college_code === academy.code)
        .map(prof => {
          // 找到属于该专业的所有班级（通过 major_code 关联）
          const classes = classRes.data
            .filter(cls => cls.major_code === prof.code)
            .map(cls => ({
              id: cls.id,
              label: cls.name,
              code: cls.code,
              type: "class",
              grade: cls.grade,
              major_code: cls.major_code,
              college_code: cls.college_code
            }));

          return {
            id: prof.id,
            label: prof.name,
            code: prof.code,
            type: "professional",
            college_code: prof.college_code,
            college_name: prof.college_name,
            children: classes
          };
        });

      return {
        id: academy.id,
        label: academy.name,
        code: academy.code,
        type: "academy",
        created_at: academy.created_at,
        updated_at: academy.updated_at,
        children: professionals
      };
    });

    console.log("构建的树状数据:", tree);
    treeData.value = tree;
  } catch (error) {
    console.error("获取树状数据失败:", error);
    if (error.message === "数据格式错误") {
      ElMessage.error("数据格式错误，请联系管理员");
    } else {
      ElMessage.error("获取树状数据失败，请检查网络连接");
    }
  } finally {
    loading.value = false;
  }
};

// 获取学院数据
const fetchAcademyData = async () => {
  try {
    loading.value = true;
    const res = await getAcademyList({
      page: academyPagination.value.currentPage,
      size: academyPagination.value.pageSize
    });
    academyData.value = res.data.records;
    academyPagination.value.total = res.data.pagination.total;
  } catch (error) {
    console.error("获取学院数据失败:", error);
    ElMessage.error("获取学院数据失败");
  } finally {
    loading.value = false;
  }
};

// 获取专业数据
const fetchProfessionalData = async () => {
  try {
    loading.value = true;
    const res = await getProfessionalList({
      page: professionalPagination.value.currentPage,
      size: professionalPagination.value.pageSize
    });
    professionalData.value = res.data.records;
    professionalPagination.value.total = res.data.pagination.total;
  } catch (error) {
    console.error("获取专业数据失败:", error);
    ElMessage.error("获取专业数据失败");
  } finally {
    loading.value = false;
  }
};

// 获取班级数据
const fetchClassData = async () => {
  try {
    loading.value = true;
    const res = await getClassPageList({
      page: classPagination.value.currentPage,
      size: classPagination.value.pageSize
    });
    classData.value = res.data.records;
    classPagination.value.total = res.data.pagination.total;
  } catch (error) {
    console.error("获取班级数据失败:", error);
    ElMessage.error("获取班级数据失败");
  } finally {
    loading.value = false;
  }
};

// 处理标签页切换
const handleTabChange = (pane: any) => {
  const tab = pane.props.name as string;
  activeTab.value = tab;
  switch (tab) {
    case "academy":
      fetchAcademyData();
      break;
    case "professional":
      fetchProfessionalData();
      break;
    case "class":
      fetchClassData();
      break;
    case "tree":
      fetchTreeData();
      break;
  }
};

// 处理分页变化
const handleClassPageChange = (page: number) => {
  classPagination.value.currentPage = page;
  fetchClassData();
};

const handleAcademyPageChange = (page: number) => {
  academyPagination.value.currentPage = page;
  fetchAcademyData();
};

const handleProfessionalPageChange = (page: number) => {
  professionalPagination.value.currentPage = page;
  fetchProfessionalData();
};

// 处理删除
const handleDelete = async (row: Class) => {
  try {
    await ElMessageBox.confirm("确认删除该班级吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    loading.value = true;
    await deleteClass({
      id: row.id
    });
    ElMessage.success("删除成功");
    fetchClassData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  } finally {
    loading.value = false;
  }
};

// 编辑状态标记
const isEdit = ref(false);
const editId = ref<number | null>(null);

// 处理编辑
const handleEdit = (row: Class) => {
  isEdit.value = true;
  editId.value = row.id;
  // 获取专业列表
  fetchAllProfessionals();
  Object.assign(form, {
    name: row.name,
    code: row.code,
    major_code: row.major_code,
    grade: Number(row.grade),
    type: "class"
  });
  dialogVisible.value = true;
};

interface BaseForm {
  name: string;
  code: string;
}

interface ClassForm extends BaseForm {
  major_code: string;
  grade: number;
  type: "class";
}

interface AcademyForm extends BaseForm {
  type: "academy";
}

interface ProfessionalForm extends BaseForm {
  college_code: string;
  type: "professional";
}

type FormData = ClassForm | AcademyForm | ProfessionalForm;

const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const form = reactive<FormData>({
  name: "",
  code: "",
  major_code: "",
  grade: new Date().getFullYear(),
  type: "class"
});

// 表单校验规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入代码", trigger: "blur" }],
  major_code: [{ required: true, message: "请输入专业代码", trigger: "blur" }],
  grade: [
    { required: true, message: "请输入年级", trigger: "blur" },
    { type: "number", message: "年级必须为数字", trigger: "blur" }
  ],
  college_code: [{ required: true, message: "请输入学院代码", trigger: "blur" }]
});

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  switch (activeTab.value) {
    case "academy":
      Object.assign(form, {
        name: "",
        code: "",
        type: "academy"
      });
      break;
    case "professional":
      Object.assign(form, {
        name: "",
        code: "",
        college_code: "",
        type: "professional"
      });
      break;
    default:
      Object.assign(form, {
        name: "",
        code: "",
        major_code: "",
        grade: new Date().getFullYear(),
        type: "class"
      });
  }
};

// 打开新增对话框
const handleAdd = () => {
  isEdit.value = false;
  editId.value = null;
  dialogVisible.value = true;
  // 如果是新增专业，获取学院列表
  if (activeTab.value === "professional" || form.type === "professional") {
    fetchAllAcademies();
  }
  // 如果是新增班级，获取专业列表
  if (activeTab.value === "class" || form.type === "class") {
    fetchAllProfessionals();
  }
  resetForm();
};

// 处理Excel导入
const handleImport = async (uploadFile: UploadFile) => {
  if (!uploadFile.raw) return;

  const file = uploadFile.raw;
  loading.value = true;

  try {
    const workbook = new ExcelJS.Workbook();
    const arrayBuffer = await file.arrayBuffer();
    await workbook.xlsx.load(arrayBuffer);

    const worksheet = workbook.worksheets[0];
    const list = [];

    // 从第二行开始读取数据（跳过表头）
    for (let i = 2; i <= worksheet.rowCount; i++) {
      const row = worksheet.getRow(i);
      if (row.getCell(1).value) {
        // 确保不是空行
        list.push({
          code: row.getCell(1).value?.toString().trim(), // BJDM
          grade: row.getCell(2).value?.toString().trim(), // NJ
          name: row.getCell(3).value?.toString().trim(), // BJMC
          college_code: row.getCell(4).value?.toString().trim(), // USER_YXID
          college_name: row.getCell(5).value?.toString().trim(), // YXMC
          major_code: row.getCell(6).value?.toString().trim(), // USER_ZYDM
          major_name: row.getCell(7).value?.toString().trim(), // ZYMC
          xz: row.getCell(8).value?.toString().trim() // XZ
        });
      }
    }

    if (list.length === 0) {
      ElMessage.warning("Excel文件中没有有效数据");
      return;
    }

    // 调用批量导入接口
    const res = await addBatchClass({ list });
    if (res.status === "success") {
      ElMessage.success("导入成功");
      fetchClassData(); // 刷新表格数据
    } else {
      ElMessage.error(res.message || "导入失败");
    }
  } catch (error) {
    console.error("导入失败:", error);
    ElMessage.error("导入失败，请检查文件格式是否正确");
  } finally {
    loading.value = false;
  }
};

// 下载Excel模板
const downloadTemplate = () => {
  // 表头数据
  const headers = [
    "BJDM(班级代码)",
    "NJ(年级)",
    "BJMC(班级名称)",
    "USER_YXID(院系ID)",
    "YXMC(院系名称)",
    "USER_ZYDM(专业代码)",
    "ZYMC(专业名称)",
    "XZ(学制)"
  ];

  // 创建工作簿
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet("班级导入模板");

  // 添加表头
  worksheet.addRow(headers);

  // 设置列宽 - 因为添加了中文说明，所以增加列宽
  headers.forEach((_, index) => {
    worksheet.getColumn(index + 1).width = 25;
  });

  // 设置表头样式
  const headerRow = worksheet.getRow(1);
  headerRow.font = { bold: true };
  headerRow.alignment = { vertical: "middle", horizontal: "center" };

  // 导出文件
  workbook.xlsx.writeBuffer().then(buffer => {
    const blob = new Blob([buffer], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "班级导入模板.xlsx";
    link.click();
    window.URL.revokeObjectURL(url);
  });
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        loading.value = true;
        if (form.type === "class") {
          const params = {
            name: form.name,
            code: form.code,
            major_code: form.major_code,
            grade: form.grade
          };

          if (isEdit.value && editId.value) {
            await updateClass({
              id: editId.value,
              ...params
            });
          } else {
            await addClass(params);
          }
        } else if (form.type === "academy") {
          const params = {
            name: form.name,
            code: form.code
          };

          if (isEdit.value && editId.value) {
            await updateAcademyList({
              id: editId.value,
              ...params
            });
          } else {
            await addAcademyList(params);
          }
        } else if (form.type === "professional") {
          const params = {
            name: form.name,
            code: form.code,
            college_code: (form as ProfessionalForm).college_code
          };

          if (isEdit.value && editId.value) {
            await updateProfessional({
              id: editId.value,
              ...params
            });
          } else {
            await addProfessional(params);
          }
        }

        ElMessage.success(isEdit.value ? "修改成功" : "添加成功");
        dialogVisible.value = false;

        // 重置编辑状态
        isEdit.value = false;
        editId.value = null;

        // 刷新对应的表格数据
        switch (form.type) {
          case "academy":
            fetchAcademyData();
            break;
          case "professional":
            fetchProfessionalData();
            break;
          case "class":
            fetchClassData();
            break;
        }

        // 如果当前是树状图视图，刷新树状数据
        if (activeTab.value === "tree") {
          fetchTreeData();
        }
      } catch (error) {
        console.error(isEdit.value ? "修改失败:" : "添加失败:", error);
        ElMessage.error(isEdit.value ? "修改失败" : "添加失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

// 处理学院删除
const handleAcademyDelete = async (row: Academy) => {
  try {
    await ElMessageBox.confirm("确认删除该学院吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    loading.value = true;
    await deleteAcademyList({
      id: row.id
    });
    ElMessage.success("删除成功");
    fetchAcademyData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  } finally {
    loading.value = false;
  }
};

// 处理专业删除
const handleProfessionalDelete = async (row: Professional) => {
  try {
    await ElMessageBox.confirm("确认删除该专业吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    loading.value = true;
    await deleteProfessional({
      id: row.id
    });
    ElMessage.success("删除成功");
    fetchProfessionalData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  } finally {
    loading.value = false;
  }
};

// 处理学院编辑
const handleAcademyEdit = (row: Academy) => {
  isEdit.value = true;
  editId.value = row.id;
  Object.assign(form, {
    name: row.name,
    code: row.code,
    type: "academy"
  });
  dialogVisible.value = true;
};

// 处理专业编辑
const handleProfessionalEdit = (row: Professional) => {
  isEdit.value = true;
  editId.value = row.id;
  fetchAllAcademies();
  Object.assign(form, {
    name: row.name,
    code: row.code,
    college_code: row.college_code,
    type: "professional"
  });
  dialogVisible.value = true;
};

// 计算属性：根据表单类型获取特定字段
const professionalForm = computed(() =>
  form.type === "professional" ? (form as ProfessionalForm) : null
);
const classForm = computed(() =>
  form.type === "class" ? (form as ClassForm) : null
);

// 处理节点点击
const handleNodeClick = (data: any) => {
  console.log(data);
};

// 处理树节点新增
const handleTreeAdd = (data: any) => {
  isEdit.value = false;
  editId.value = null;

  if (data.type === "academy") {
    // 新增专业
    fetchAllAcademies();
    Object.assign(form, {
      name: "",
      code: "",
      college_code: data.code,
      type: "professional"
    });
  } else if (data.type === "professional") {
    // 新增班级
    fetchAllProfessionals();
    Object.assign(form, {
      name: "",
      code: "",
      major_code: data.code,
      grade: new Date().getFullYear(),
      type: "class"
    });
  }

  dialogVisible.value = true;
};

// 处理树节点编辑
const handleTreeEdit = (data: any) => {
  isEdit.value = true;
  editId.value = data.id;

  switch (data.type) {
    case "academy":
      Object.assign(form, {
        name: data.label,
        code: data.code,
        type: "academy"
      });
      break;
    case "professional":
      fetchAllAcademies();
      Object.assign(form, {
        name: data.label,
        code: data.code,
        college_code: data.college_code,
        type: "professional"
      });
      break;
    case "class":
      fetchAllProfessionals();
      Object.assign(form, {
        name: data.label,
        code: data.code,
        major_code: data.major_code,
        grade: Number(data.grade),
        type: "class"
      });
      break;
  }

  dialogVisible.value = true;
};

// 处理树节点删除
const handleTreeDelete = async (data: any) => {
  try {
    await ElMessageBox.confirm(
      `确认删除该${
        data.type === "academy"
          ? "学院"
          : data.type === "professional"
            ? "专业"
            : "班级"
      }吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    loading.value = true;
    switch (data.type) {
      case "academy":
        await deleteAcademyList({ id: data.id });
        break;
      case "professional":
        await deleteProfessional({ id: data.id });
        break;
      case "class":
        await deleteClass({ id: data.id });
        break;
    }

    ElMessage.success("删除成功");
    fetchTreeData(); // 刷新树状数据
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchClassData();
});
</script>

<template>
  <div class="class-container">
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="title">教务管理</span>
          <el-tabs
            v-model="activeTab"
            class="header-tabs"
            @tab-click="handleTabChange"
          >
            <el-tab-pane label="学院管理" name="academy" />
            <el-tab-pane label="专业管理" name="professional" />
            <el-tab-pane label="班级管理" name="class" />
            <el-tab-pane label="树状图" name="tree" />
          </el-tabs>
        </div>
      </template>

      <div v-show="activeTab === 'academy'">
        <div class="table-toolbar">
          <el-button type="primary" @click="handleAdd">新增学院</el-button>
        </div>
        <el-table v-loading="loading" :data="academyData" border>
          <el-table-column prop="name" label="学院名称" align="center" />
          <el-table-column prop="code" label="学院代码" align="center" />
          <el-table-column prop="created_at" label="创建时间" align="center" />
          <el-table-column prop="updated_at" label="更新时间" align="center" />
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="handleAcademyEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleAcademyDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            v-model:current-page="academyPagination.currentPage"
            :page-size="academyPagination.pageSize"
            :total="academyPagination.total"
            layout="prev, pager, next, total"
            @current-change="handleAcademyPageChange"
          />
        </div>
      </div>

      <div v-show="activeTab === 'professional'">
        <div class="table-toolbar">
          <el-button type="primary" @click="handleAdd">新增专业</el-button>
        </div>
        <el-table v-loading="loading" :data="professionalData" border>
          <el-table-column prop="name" label="专业名称" align="center" />
          <el-table-column prop="code" label="专业代码" align="center" />
          <el-table-column prop="college_name" label="所属学院" align="center">
            <template #default="{ row }">
              <span>{{ row.college_name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="college_code"
            label="学院代码"
            align="center"
          />
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="handleProfessionalEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleProfessionalDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            v-model:current-page="professionalPagination.currentPage"
            :page-size="professionalPagination.pageSize"
            :total="professionalPagination.total"
            layout="prev, pager, next, total"
            @current-change="handleProfessionalPageChange"
          />
        </div>
      </div>

      <div v-show="activeTab === 'class'">
        <div class="table-toolbar">
          <el-button type="primary" @click="handleAdd">新增班级</el-button>
          <el-button type="success" @click="downloadTemplate"
            >下载模板</el-button
          >
          <el-upload
            class="upload-excel"
            accept=".xlsx"
            :show-file-list="false"
            :auto-upload="false"
            @change="handleImport"
          >
            <el-button type="primary">导入Excel</el-button>
          </el-upload>
        </div>
        <el-table v-loading="loading" :data="classData" border>
          <el-table-column prop="college_name" label="所属学院" align="center">
            <template #default="{ row }">
              <span>{{ row.college_name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="major_name" label="所属专业" align="center">
            <template #default="{ row }">
              <span>{{ row.major_name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="班级名称" align="center" />
          <el-table-column prop="code" label="班级代码" align="center" />
          <el-table-column prop="grade" label="年级" align="center" />
          <el-table-column label="操作" width="200" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            v-model:current-page="classPagination.currentPage"
            :page-size="classPagination.pageSize"
            :total="classPagination.total"
            layout="prev, pager, next, total"
            @current-change="handleClassPageChange"
          />
        </div>
      </div>

      <!-- 树状视图 -->
      <div v-show="activeTab === 'tree'" class="tree-view">
        <el-tree
          :data="treeData"
          :props="{
            children: 'children',
            label: 'label'
          }"
          node-key="id"
          highlight-current
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span class="node-code">({{ data.code }})</span>
              <el-tag
                size="small"
                :type="
                  data.type === 'academy'
                    ? 'primary'
                    : data.type === 'professional'
                      ? 'success'
                      : 'warning'
                "
                class="node-type"
              >
                {{
                  data.type === "academy"
                    ? "学院"
                    : data.type === "professional"
                      ? "专业"
                      : "班级"
                }}
              </el-tag>
              <span class="node-actions">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click.stop="handleTreeAdd(data)"
                >
                  新增{{
                    data.type === "academy"
                      ? "专业"
                      : data.type === "professional"
                        ? "班级"
                        : ""
                  }}
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click.stop="handleTreeEdit(data)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  link
                  @click.stop="handleTreeDelete(data)"
                >
                  删除
                </el-button>
              </span>
            </span>
          </template>
        </el-tree>
      </div>

      <!-- 新增对话框，根据activeTab显示不同的表单 -->
      <el-dialog
        v-model="dialogVisible"
        :title="
          form.type === 'class'
            ? '新增班级'
            : form.type === 'professional'
              ? '新增专业'
              : '新增学院'
        "
        width="500px"
        :close-on-click-modal="false"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          label-position="right"
        >
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="form.name"
              :placeholder="
                '请输入' +
                (form.type === 'class'
                  ? '班级'
                  : form.type === 'professional'
                    ? '专业'
                    : '学院') +
                '名称'
              "
            />
          </el-form-item>
          <el-form-item label="代码" prop="code">
            <el-input
              v-model="form.code"
              :placeholder="
                '请输入' +
                (form.type === 'class'
                  ? '班级'
                  : form.type === 'professional'
                    ? '专业'
                    : '学院') +
                '代码'
              "
            />
          </el-form-item>

          <!-- 专业表单特有字段 -->
          <template v-if="professionalForm">
            <el-form-item label="所属学院" prop="college_code">
              <el-select
                v-model="professionalForm.college_code"
                placeholder="请选择所属学院"
                style="width: 100%"
              >
                <el-option
                  v-for="academy in allAcademies"
                  :key="academy.code"
                  :label="academy.name"
                  :value="academy.code"
                >
                  <span>{{ academy.name }}</span>
                  <span style="float: right; font-size: 13px; color: #8492a6">
                    {{ academy.code }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </template>

          <!-- 班级表单特有字段 -->
          <template v-if="classForm">
            <el-form-item label="所属专业" prop="major_code">
              <el-select
                v-model="classForm.major_code"
                placeholder="请选择所属专业"
                style="width: 100%"
              >
                <el-option
                  v-for="professional in allProfessionals"
                  :key="professional.code"
                  :label="professional.name"
                  :value="professional.code"
                >
                  <span>{{ professional.name }}</span>
                  <span style="float: right; font-size: 13px; color: #8492a6">
                    {{ professional.code }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="年级" prop="grade">
              <el-input-number
                v-model="classForm.grade"
                :min="2000"
                :max="2100"
                placeholder="请输入年级"
                style="width: 100%"
              />
            </el-form-item>
          </template>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.class-container {
  padding: 20px;

  .table-card {
    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .title {
        font-size: 16px;
        font-weight: bold;
      }

      .header-tabs {
        margin-left: auto;

        :deep(.el-tabs__header) {
          margin: 0;
        }
      }
    }

    .table-toolbar {
      display: flex;
      gap: 10px;
      margin-bottom: 16px;

      .upload-excel {
        display: inline-block;
      }
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }

  :deep(.el-tag) {
    margin-right: 5px;
  }

  .el-button {
    margin-right: 10px;
  }

  .dialog-footer {
    .el-button {
      margin-left: 10px;
    }
  }

  .tree-view {
    padding: 20px;

    .custom-tree-node {
      display: flex;
      flex: 1;
      gap: 8px;
      align-items: center;

      .node-code {
        font-size: 12px;
        color: #666;
      }

      .node-type {
        margin-left: 8px;
      }

      .node-actions {
        margin-left: auto;
        opacity: 0;
        transition: opacity 0.2s;
      }

      &:hover {
        .node-actions {
          opacity: 1;
        }
      }
    }
  }
}
</style>
